<?php 
/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-12 15:43:11 +0200 (Sat, 12 Jul 2008) $
 * $Rev: 1291 $
 * $Author: gavinspearhead $
 * $Id: ajax_showtransfers.php 1291 2008-07-12 13:43:11Z gavinspearhead $
 */
define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);
$__auth = 'silent';

$pathajt = realpath(dirname(__FILE__));

require_once "$pathajt/../functions/ajax_includes.php";
	
$STATUS = '';
if ($isadmin) {
	// Admins can see any download
    $sql1 = 'SELECT * FROM downloadinfo WHERE "preview" =\''. DLTYPE_NORMAL .'\' ORDER BY "status" ASC, "position" ASC, "ID" DESC';
    $sql2 = 'SELECT * FROM postinfo ORDER BY "status" ASC, "id" DESC'; 
} else {
	$username = get_username($db, $userID);
	if ($username === FALSE)
		fatal_error($LN['error_haxor']);
	$sql1 = "SELECT * FROM downloadinfo WHERE \"username\" = '$username' AND \"preview\" ='" .  DLTYPE_NORMAL . "' ORDER BY \"status\" ASC, \"position\" ASC, \"ID\" DESC";
	$sql2 = "SELECT * FROM postinfo WHERE \"userid\" = '$userID' ORDER BY \"status\" ASC, \"id\" DESC";
}

// Get download info:
$res1 = $db->execute_query($sql1);
$res2 = $db->execute_query($sql2);
if ($res1 === FALSE) 
	$res1 = array();
if ($res2 === FALSE) 
	$res2 = array();
$infoarray = $infoarray_upload = array();
$urdd_online = check_urdd_online();


class UploadInfo
{
	public $status;
	public $name;
	public $size;
	public $startdate;
	public $progress;
	public $speed;
	public $ETA;
	public $linkview;
	public $postid;
	public $username;
}
  

class DownloadInfo
{
	public $status;
	public $name;
	public $size;
	public $startdate;
	public $progress;
	public $speed;
	public $ETA;
	public $linkview;
	public $dlid;
    public $username;
}
  
$poster = is_poster($db, $userID);

// parse downloads
foreach ($res1 as $row) {
	$dlname = $row['name'];
	$dlid = $row['ID'];
	$dest = $row['destination'];
	$size = $row['size'];
	$status = $row['status'];
	$username = $row['username'];
	$start_time = $row['start_time'];

	// Get more information for this download (when it's in progress:)
    $sql = "SELECT * FROM queueinfo WHERE \"description\" = '" . get_command(COMMAND_DOWNLOAD_ACTION) . " $dlid' OR "
        . " (\"description\" = '" . get_command(COMMAND_DOWNLOAD) . " $dlid' AND \"status\" NOT IN ( '" . QUEUE_FINISHED . '\',\'' . QUEUE_REMOVED . "'))";
    $res3 = $db->execute_query($sql);
	if ($res3 === FALSE || $db->num_rows() == 0) 
		continue;

	$starttime = time() + 3600; // Should always be in the future
	$stoptime = 0; // Should always be in the past
	$maxperc = 0;
	$minperc = 100;
	$qstatus = '';
	$ETA = 0;
	foreach ($res3 as $queue) {
		$qstatus = $queue['status'];
		if ($qstatus !== QUEUE_CANCELLED)
			$maxperc = max($maxperc, $queue['progress']);
		$stoptime = max($stoptime, $queue['lastupdate']);
		if ($queue['ETA'] > 0)
			$ETA = ($ETA == 0) ? $queue['ETA'] : min($ETA, $queue['ETA']);
	}
	$dltime = $stoptime - $start_time;
		$fETA = ($ETA > 0) ? readable_time($ETA, 'fancy') :  '';
	if ($fETA == '0' || $fETA == '?') 
		$fETA = '';

	$done = $maxperc;
	$remain = 100 - $done;
	$percentage = $done . '%';
	$startdate = date($LN['dateformat3'], $start_time);
	$starttime = date($LN['timeformat'], $start_time);

	// "Calculate" download speed:
	$speed = '';
	if ($ETA > 0) {
		$speed = $size * $remain / 100 / $ETA;	// 4 GB * 20% / ETA -> bytes per second
		$speed /= 1024;		// KB/s
		$speed *= 1.05;		// Compensate for overhead in transmission 
		$speed = floor($speed);
		$speed .= ' K' . $LN['byte_short'] . '/s';
	}

	// Friendly status name:
	switch ($status) {
		case DOWNLOAD_READY:    $cat = 'ready'; break;
		case DOWNLOAD_QUEUED:   $cat = 'queued'; break;
		case DOWNLOAD_ACTIVE:   $cat = 'active'; break;
		case DOWNLOAD_FINISHED: $cat = 'finished'; break;
		case DOWNLOAD_CANCELLED:$cat = 'cancelled'; break;
		case DOWNLOAD_PAUSED:   $cat = 'paused'; break;
		case DOWNLOAD_STOPPED:  $cat = 'stopped'; break;
		case DOWNLOAD_SHUTDOWN: $cat = 'shutdown'; break;
		case DOWNLOAD_ERROR:    $cat = 'error'; break;
		case DOWNLOAD_COMPLETE: $cat = 'complete'; break;
		case DOWNLOAD_RAR_FAILED : $cat = 'rarfailed'; break;
		case DOWNLOAD_PAR_FAILED : $cat = 'par2failed'; break;
		case DOWNLOAD_CKSFV_FAILED : $cat = 'cksfvfailed'; break;
		case DOWNLOAD_FAILED:   $cat = 'dlfailed'; break;
		default : $cat = 'unknown'; break;
	}

	$info = new DownloadInfo();
	$info->status = $cat;
	$info->name = $dlname;
	$info->ETA = $fETA;
	$info->startdate = $startdate . ' '. $starttime;
	$info->progress = $percentage;
	$info->speed = $speed;
	$info->done = $done;
	$info->remain = $remain;
	$info->linkview = 'viewfiles.php?dir=' . $dest;
	$info->directory = 'getfile.php?file=' . $dest;
	$info->dlid = $dlid;
	$info->username = $username;
	$info->size = readable_size($size, 1, $LN['byte_short']);
	// Cleanup:
	if ($status != DOWNLOAD_ACTIVE) {
		$info->ETA = '';
		$info->speed = '';
	}
	$infoarray[] = $info;
}

// parse upload-
foreach ($res2 as $row) {
	$dlname = $row['subject'];
	$postid = $row['id'];
	$group = group_name($db, $row['groupid']);
	$size = $row['size'];
	$status = $row['status'];
    $username = get_username($db, $row['userid']);

    $start_time = $row['start_time'];

	// Get more information for this download (when it's in progress:)
    $sql = "SELECT * FROM queueinfo WHERE \"description\" = '" . get_command(COMMAND_POST_ACTION) . " $postid' OR "
        . " (\"description\" = '" . get_command(COMMAND_POST) . " $postid' AND \"status\" NOT IN ( '" . QUEUE_FINISHED . '\',\'' . QUEUE_REMOVED . "')) OR"
        . " (\"description\" = '" . get_command(COMMAND_START_POST) . " $postid' AND \"status\" NOT IN ( '" . QUEUE_FINISHED . '\',\'' . QUEUE_REMOVED . "'))";
    $res3 = $db->execute_query($sql);
	if ($res3 === FALSE || $db->num_rows() == 0) 
		continue;

	$starttime = time() + 3600; // Should always be in the future
	$stoptime = 0; // Should always be in the past
	$maxperc = 0;
	$minperc = 100;
	$qstatus = '';
    $ETA = 0;
	foreach ($res3 as $queue) {
		$qstatus = $queue['status'];
		if ($qstatus !== QUEUE_CANCELLED)
			$maxperc = max($maxperc, $queue['progress']);
		$stoptime = max($stoptime, $queue['lastupdate']);
		if ($queue['ETA'] > 0)
			$ETA = ($ETA <= 0) ? $queue['ETA'] : min($ETA, $queue['ETA']);
	}
	$dltime = $stoptime - $start_time;
    $fETA = ($ETA > 0) ? readable_time($ETA, 'fancy') :  '';
	if ($fETA == '0' || $fETA == '?') 
		$fETA = '';

	$done = $maxperc;
	$remain = 100 - $done;
	$percentage = $done . '%';
	$startdate = date('j M', $start_time);
	$starttime = date('H:i:s', $start_time);

	// "Calculate" download speed:
	$speed = '';
	if ($ETA > 0) {
		$speed = $size * $remain / 100 / $ETA;	// 4 GB * 20% / ETA -> bytes per second
		$speed /= 1024;		// KB/s
		$speed *= 1.05;		// Compensate for overhead in transmission 
		$speed = floor($speed);
		$speed .= ' K' . $LN['byte_short'] . '/s';
	}

	// Friendly status name:
	switch ($status) {
		case POST_READY:      $cat = 'ready'; break;
		case POST_QUEUED:     $cat = 'queued'; break;
		case POST_ACTIVE:     $cat = 'active'; break;
		case POST_FINISHED:   $cat = 'finished'; break;
		case POST_CANCELLED:  $cat = 'cancelled'; break;
		case POST_PAUSED:     $cat = 'paused'; break;
		case POST_STOPPED:    $cat = 'stopped'; break;
		case POST_SHUTDOWN:   $cat = 'shutdown'; break;
		case POST_ERROR:      $cat = 'error'; break;
		case POST_RARRED :    $cat = 'rarred'; break;
		case POST_PARRED :    $cat = 'par2ed'; break;
        case POST_YYENCODED : $cat = 'yyencoded'; break;
        case POST_RAR_FAILED: $cat = 'rarfailed'; break;
        case POST_PAR_FAILED: $cat = 'par2failed'; break;
        case POST_YYENCODE_FAILED: $cat = 'yyencodefailed'; break;
        default :             $cat = 'unknown'; break;
    }

	$info = new UploadInfo();
	$info->status = $cat;
	$info->name = $dlname;
	$info->ETA = $fETA;
	$info->startdate = $startdate . ' '. $starttime;
	$info->progress = $percentage;
	$info->speed = $speed;
	$info->done = $done;
	$info->remain = $remain;
	$info->postid = $postid;
	$info->username = $username;
	$info->size = readable_size($size, 0, $LN['byte_short']);
	// Cleanup:
	if ($status != POST_ACTIVE) {
		$info->ETA = '';
		$info->speed = '';
	}
    $infoarray_upload[] = $info;
    
}


if(!isset($_SESSION['post_hide_status'])) 
    set_post_status();

if(!isset($_SESSION['transfer_hide_status'])) 
    set_down_status();


$challenge = set_challenge();
$smarty->assign('transfer_hide_status', $_SESSION['transfer_hide_status']);
$smarty->assign('post_hide_status',     $_SESSION['post_hide_status']);
$smarty->assign('maxstrlen',		    $prefs['maxsetname']/2);
$smarty->assign('infoarray',    	    $infoarray);
$smarty->assign('infoarray_upload',    	$infoarray_upload);
$smarty->assign('challenge',    	    $challenge);
$smarty->assign('poster',         	    $poster?1:0);
$smarty->assign('isadmin',         	    $isadmin?1:0);
$smarty->assign('urdd_online',    	    (int)$urdd_online);
$smarty->assign('offline_message',      $LN['enableurddfirst'] );
$smarty->display('ajax_showtransfers.tpl');


?>
